#include <stdio.h>
#include <string.h>
#include<stdarg.h>
#include "util.h"

int patternPrint(char*fmt,char*result,int index,int*start,int*end){
	char temp=0;
	int fmtStart=-1;
	do{
		temp=fmt[index];
		index++;
		if(fmtStart>=0&&(temp=='d'||temp=='s'||temp=='x'||temp=='X'||temp=='c')){
			result[fmtStart]=temp;
			result[fmtStart+1]=0;
			*end=index-1;
			break;
		}
		if(temp=='%'){
			*start=index-1;
			fmtStart=0;
		}
		if(fmtStart<0||((fmtStart>0)&&(temp=='%'&&fmt[index]=='%'))){
			printf("%c",temp);
		}


		if(fmtStart>=0){
			result[fmtStart]=temp;
			fmtStart++;
		}

	}while(temp!=0);
	return fmtStart;
}

int loadCode(char*fileName,char*data){
	FILE*f=fopen(fileName,"rb");
	if(f==NULL){
		printf("not open file\r\n");
	}
	int rt=fread(data,1,1024,f);
	fclose(f);
	return rt;	
}

int getParamSize(Register*R){
	return R->RAX;
}


char*getStringParam(Register*R,int index){
	char*code=R->code;
	int top=R->RSS+R->RSP-4-index*4;
	u32 address=byte2int(code[top+3],code[top+2],code[top+1],code[top+0]);
	char*str=(char*)(code+address);
	return str;
}

int getIntParam(Register*R,int index){
	char*code=R->code;
	int top=R->RSS+R->RSP-4-index*4;
	u32 address=byte2int(code[top+3],code[top+2],code[top+1],code[top+0]);
	return address;
}
char getCharParam(Register*R,int index){
	char*code=R->code;
	int top=R->RSS+R->RSP-4-index*4;
	u32 address=byte2int(code[top+3],code[top+2],code[top+1],code[top+0]);
	return address&0xFF;
}

int sleep(Register*R){
	int number=getIntParam(R,0);
	printf("time:%d\r\n",number);
	return 0;
}
int gpio(Register*R){
	int port=getIntParam(R,0);
	int state=getIntParam(R,1);
	printf("port:%d,state:%d\r\n",port,state);
	return 0;
}


int print(Register*R){
	char*code=R->code;
	int top=R->RSS+R->RSP-4;
	u32 address=byte2int(code[top+3],code[top+2],code[top+1],code[top+0]);
	char*fmt=(char*)(code+address);
	int paramSize=getParamSize(R);
	if(paramSize<2){
		printf("%s",fmt);
		return 0;
	}

	char buf[20]={0};
	int index=0;
	int start;
	int end;
	int bufSize=0;
	char bufChar=0;
	int paramIndex=1;
	while(1){
		int ret=patternPrint(fmt,buf,index,&start,&end);
		if(ret<0){
			break;
		}
		if(start>end){
			break;
		}
		//打印需要格式化的数据
		bufSize=strlen(buf);
		if(bufSize>0){
			bufChar=buf[bufSize-1];
			if(bufChar=='s'){
				char *str=getStringParam(R,paramIndex);
				printf(buf,str);
				paramIndex++;
			}else if(bufChar=='d'||bufChar=='X'||bufChar=='x'){
				int number=getIntParam(R,paramIndex);
				printf(buf,number);
				paramIndex++;
			}else if(bufChar=='c'){
				char cc=getCharParam(R,paramIndex);
				printf(buf,cc);
				paramIndex++;
			}
			
		}
		
		index=end+1;

	}


	return 0;
}
